package com.example.app.controller;

import com.example.app.entity.BodyEntry;
import com.example.app.service.BodyEntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api/body-entries")
public class BodyEntryController {

    @Autowired
    private BodyEntryService service;

    @GetMapping
    public List<BodyEntry> getAll() {
        return service.getAllEntries();
    }

    @GetMapping("/user/{userId}")
    public List<BodyEntry> getByUserId(@PathVariable Long userId) {
        return service.getEntriesByUserId(userId);
    }

    @GetMapping("/user/{userId}/date/{date}")
    public ResponseEntity<BodyEntry> getByUserIdAndDate(
            @PathVariable Long userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

        return service.getEntryByUserIdAndDate(userId, date)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public BodyEntry addOrUpdate(@RequestBody BodyEntry entry) {
        return service.addOrUpdateEntry(entry);
    }

    @DeleteMapping("/{entryId}")
    public ResponseEntity<Void> delete(@PathVariable Long entryId) {
        service.deleteEntry(entryId);
        return ResponseEntity.noContent().build();
    }

    @DeleteMapping("/user/{userId}/date/{date}")
    public ResponseEntity<String> deleteByUserIdAndDate(@PathVariable Long userId, @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        boolean deleted = service.deleteByUserIdAndDate(userId, date);
        if (deleted) {
            return ResponseEntity.ok("记录已删除");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到对应记录");
        }
    }
}